package com.geek.water.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.geek.water.constant.BillingConstants;
import com.geek.water.entity.GlobalWaterPriceTier;
import com.geek.water.mapper.GlobalWaterPriceTierMapper;
import com.geek.water.service.GlobalWaterPriceTierService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
 * 全局阶梯水费配置服务实现类
 * @author yangwenqi
 * @date 2025/8/7
 */
@Slf4j
@Service
public class GlobalWaterPriceTierServiceImpl extends ServiceImpl<GlobalWaterPriceTierMapper, GlobalWaterPriceTier> implements GlobalWaterPriceTierService {

    @Override
    public List<GlobalWaterPriceTier> getActiveTiers() {
        LambdaQueryWrapper<GlobalWaterPriceTier> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GlobalWaterPriceTier::getIsActive, true)
                .orderByAsc(GlobalWaterPriceTier::getSortOrder);
        return this.list(wrapper);
    }

    @Override
    public BigDecimal calculateGlobalTieredPrice(BigDecimal usageAmount) {
        if (usageAmount == null || usageAmount.compareTo(BigDecimal.ZERO) <= 0) {
            return BillingConstants.MIN_BILLING_AMOUNT;
        }

        // 获取全局阶梯水费配置
        List<GlobalWaterPriceTier> tiers = getActiveTiers();

        // 如果没有配置阶梯水费，使用默认单价
        if (tiers.isEmpty()) {
            return usageAmount.multiply(BillingConstants.DEFAULT_WATER_PRICE);
        }

        BigDecimal totalAmount = BigDecimal.ZERO;
        BigDecimal remainingUsage = usageAmount;

        for (GlobalWaterPriceTier tier : tiers) {
            if (remainingUsage.compareTo(BigDecimal.ZERO) <= 0) {
                break;
            }

            BigDecimal tierMinUsage = tier.getMinUsage() != null ? tier.getMinUsage() : BigDecimal.ZERO;
            BigDecimal tierMaxUsage = tier.getMaxUsage();
            BigDecimal tierUnitPrice = tier.getUnitPrice();

            // 计算当前阶梯的可用用量
            BigDecimal tierUsage;
            if (tierMaxUsage == null) {
                // 无上限阶梯
                tierUsage = remainingUsage;
            } else {
                // 有上限阶梯
                BigDecimal tierRange = tierMaxUsage.subtract(tierMinUsage);
                tierUsage = remainingUsage.compareTo(tierRange) > 0 ? tierRange : remainingUsage;
            }

            // 计算当前阶梯的费用
            BigDecimal tierAmount = tierUsage.multiply(tierUnitPrice);
            totalAmount = totalAmount.add(tierAmount);
            remainingUsage = remainingUsage.subtract(tierUsage);

            log.debug("全局阶梯 {}: 用量={}, 单价={}, 费用={}",
                    tier.getTierName(), tierUsage, tierUnitPrice, tierAmount);
        }

        // 保留两位小数
        return totalAmount.setScale(2, RoundingMode.HALF_UP);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveGlobalTiers(List<GlobalWaterPriceTier> tiers) {
        // 删除所有现有的全局阶梯配置
        this.remove(null);

        // 保存新的阶梯配置
        if (tiers != null && !tiers.isEmpty()) {
            for (int i = 0; i < tiers.size(); i++) {
                GlobalWaterPriceTier tier = tiers.get(i);
                tier.setSortOrder(i + 1);
                tier.setIsActive(true);
            }
            this.saveBatch(tiers);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void initializeDefaultTiers() {
        // 检查是否已有配置
        long count = this.count();
        if (count > 0) {
            log.info("全局阶梯水费配置已存在，跳过初始化");
            return;
        }

        List<GlobalWaterPriceTier> defaultTiers = new ArrayList<>();

        // 第一阶梯：0-10吨，3.50元/吨
        GlobalWaterPriceTier tier1 = new GlobalWaterPriceTier();
        tier1.setTierName("第一阶梯");
        tier1.setMinUsage(new BigDecimal("0.00"));
        tier1.setMaxUsage(new BigDecimal("10.00"));
        tier1.setUnitPrice(new BigDecimal("3.50"));
        tier1.setSortOrder(1);
        tier1.setIsActive(true);
        tier1.setRemark("基础用水量,单价较低");
        defaultTiers.add(tier1);

        // 第二阶梯：10-50吨，4.20元/吨
        GlobalWaterPriceTier tier2 = new GlobalWaterPriceTier();
        tier2.setTierName("第二阶梯");
        tier2.setMinUsage(new BigDecimal("10.00"));
        tier2.setMaxUsage(new BigDecimal("50.00"));
        tier2.setUnitPrice(new BigDecimal("4.20"));
        tier2.setSortOrder(2);
        tier2.setIsActive(true);
        tier2.setRemark("中等用水量,单价适中");
        defaultTiers.add(tier2);

        // 第三阶梯：50吨以上，5.00元/吨
        GlobalWaterPriceTier tier3 = new GlobalWaterPriceTier();
        tier3.setTierName("第三阶梯");
        tier3.setMinUsage(new BigDecimal("50.00"));
        tier3.setMaxUsage(null); // 无上限
        tier3.setUnitPrice(new BigDecimal("5.00"));
        tier3.setSortOrder(3);
        tier3.setIsActive(true);
        tier3.setRemark("高用水量,单价较高");
        defaultTiers.add(tier3);

        this.saveBatch(defaultTiers);
        log.info("全局阶梯水费配置初始化完成");
    }
}